class FacebookController < ActionController::Base
  helper_method :current_facebook_user, :current_facebook_client
  
  def current_facebook_user
    return @current_facebook_user if defined?(@current_facebook_user)
    @current_facebook_user = Mogli::User.find("me",current_facebook_client)  
  rescue Exception
    @current_facebook_user = nil
  end
  
  
  def ensure_is_authenticated_in_fb
    #check if any session exists  
    if (!current_user_session || !current_user.is_fb_authorized  || !current_facebook_user || !is_authenticated_in_fb) && is_running_on_fb
      #if (!current_user_session)
      html = ""
      html +="<script>"
      html +="window.top.location.href=\"#{new_oauth_url}\""
      html +="</script>"
      render :text=>html
    end
  end
  
  def is_authenticated_in_fb
    return false if params[:fb_sig_logged_out_facebook]
    return true
  end
  
  def is_running_on_fb
    return true if params[:fb_sig_app_id] 
    return false
  end
  
  def current_facebook_client
    return @current_facebook_client if defined?(@current_facebook_client)
    @current_facebook_client = Mogli::Client.new(current_user.fb_at)
  end
  
end   
